import { AfterViewInit, ChangeDetectorRef, Component, OnInit, ViewChild } from '@angular/core';
import { AfMessageService, AfNavigationService } from '@core';
import { _HttpClient } from '@delon/theme';
import { NzModalService, NzModalRef } from 'ng-zorro-antd/modal';
import { NzFormatEmitEvent, NzTreeComponent, NzTreeNode, NzTreeNodeOptions } from 'ng-zorro-antd/tree';

import { SecurityService } from '../security.service';

@Component({
  selector: 'app-security-menu',
  templateUrl: './menu.component.html'
})
export class SecurityMenuComponent implements OnInit {
  @ViewChild('nzTreeComponent', { static: false }) nzTreeComponent!: NzTreeComponent;
  currentRecord: any;
  selectRecord: any;
  menuTitle: any = '';
  // defaultSelectedKeys = ['1'];

  newRecord() {
    return {
      id: '',
      pid: '',
      text: '',
      i18n: '',
      group: true,
      link: '',
      externalLink: '',
      target: '',
      icon: '',
      badge: '',
      shortcut: false,
      shortcutRoot: false,
      sort: '',
      hide: false,
      disabled: false
    };
  }

  constructor(
    private http: _HttpClient,
    private modal: NzModalService,
    private cdr: ChangeDetectorRef,
    private msgSrv: AfMessageService,
    private navSrv: AfNavigationService,
    private securitySrv: SecurityService
  ) {
    this.queryMenuTree();
    this.currentRecord = this.newRecord();
  }

  ngOnInit(): void {
    this.queryMenuIcon();
    this.cdr.detectChanges();
    setTimeout(() => {
      this.cdr.detectChanges();
    }, 100);
  }

  menuIconList: any[] = [];
  queryMenuIcon() {
    this.securitySrv.queryMenuIcon().subscribe(body => {
      if (body.status) {
        console.log(JSON.stringify(body));
        this.menuIconList = body.data;
      }
    });
  }

  menuTree: any[] = [];
  queryMenuTree() {
    console.log('queryMenuTree');
    this.securitySrv.queryMenuTree().subscribe(body => {
      console.log(JSON.stringify(body));
      if (body.status) {
        this.menuTree = body.data;
      }
    });
  }

  treeNodeDbClick(event: NzFormatEmitEvent): void {
    this.currentRecord = event.node?.origin;
  }

  treeNodeClick(event: NzFormatEmitEvent): void {
    this.selectRecord = event.node?.origin;
  }

  nzDrop(event: NzFormatEmitEvent): void {
    console.log(event);
    const drapNode: any = event.dragNode?.origin;
    const id = drapNode.id;
    const parentNode: any = event.dragNode?.parentNode?.origin;
    const pid = parentNode ? parentNode.id : 0;

    console.log(`id=${id}; pid=${pid}`);
    this.securitySrv.dropMenuTree(id, pid).subscribe(body => {
      // console.log(JSON.stringify(body));
      if (body.status) {
        this.msgSrv.msg_success('保存成功');
        // this.queryMenuTree();
      } else {
        this.msgSrv.msg_warning(body.msg);
      }
    });

    console.log(event);
  }
  cardIsLoading() {
    if (this.currentRecord.pid == null || this.currentRecord.pid === '') {
      return true;
    }
    return false;
  }

  addMenu(): void {
    if (this.nzTreeComponent.getSelectedNodeList().length <= 0) {
      this.msgSrv.msg_warning('请选择需要新建的菜单位置');
      return;
    }
    this.menuTitle = '新增同级菜单';
    this.currentRecord = this.newRecord();
    this.currentRecord.pid = this.selectRecord.pid;
    this.currentRecord.group = this.selectRecord.group;
    // console.log(this.currentRecord);
  }

  addSubMenu(): void {
    if (this.nzTreeComponent.getSelectedNodeList().length <= 0) {
      this.msgSrv.msg_warning('请选择需要新建的菜单位置');
      return;
    }
    this.menuTitle = '新增子级菜单';
    this.currentRecord = this.newRecord();
    this.currentRecord.pid = this.selectRecord.id;
    this.currentRecord.group = false;
    // console.log(this.currentRecord);
  }

  editMenu() {
    console.log(JSON.stringify(this.selectRecord));
    this.currentRecord = this.selectRecord;
    // console.log(JSON.stringify(this.currentRecord));
  }

  saveMenuTree() {
    if (this.currentRecord.text == null || this.currentRecord.text == '') {
      this.msgSrv.msg_warning('菜单名称不能为空！');
      return;
    }
    if (this.currentRecord.shortcutRoot && this.currentRecord.shortcutRoot) {
      this.msgSrv.msg_warning('不能同时开启快捷菜单和快捷菜单组！');
      return;
    }
    // if (!this.currentRecord.group) {
    //   if (
    //     (this.currentRecord.link == null || this.currentRecord.link == '') &&
    //     (this.currentRecord.externalLink == null || this.currentRecord.externalLink == '')
    //   ) {
    //     this.msgSrv.msg_warning('路由地址和外部地址，至少要输入一个');
    //     return;
    //   }
    // }
    this.securitySrv.saveMenuTree(this.currentRecord).subscribe(body => {
      console.log(JSON.stringify(body));
      if (body.status) {
        this.currentRecord.title = this.currentRecord.text;
        this.currentRecord.id = body.data;
        // console.log(`saveMenuTree:${JSON.stringify(this.currentRecord)}`);
        this.msgSrv.msg_success('保存成功');
        this.queryMenuTree();
      } else {
        this.msgSrv.msg_warning(body.msg);
      }
    });
  }

  confirmModal?: NzModalRef; // For testing by now

  deleteMenuTree() {
    if (this.currentRecord.id == null || this.currentRecord.id == '') {
      this.msgSrv.msg_warning('还未保存， 无需删除！');
      return;
    }
    this.confirmModal = this.modal.confirm({
      nzTitle: `是否确定要删除“${this.currentRecord.text}“菜单?`,
      nzContent: '确定要删除，请单击“确定”按钮时',
      nzOnOk: () => {
        this.securitySrv.deleteMenuTree(this.currentRecord.id).subscribe(body => {
          if (body.status) {
            this.currentRecord = this.newRecord();
            this.menuTitle = '';
            this.queryMenuTree();
          } else {
            this.msgSrv.msg_warning(body.msg);
          }
        });
      }
    });
  }
}
